<script setup>
import { onMounted, ref, getCurrentInstance, nextTick } from 'vue'
import Category from '../components/category/Category.vue'
import ChangeCategory from '../components/category/ChangeCategory.vue'
import request from '../api/index'
import { getFileTypeFromExtension } from '../utils/file'
const proxy = getCurrentInstance()?.proxy
const titleFunction = [
  {
    type: 'button',
    text: '上传',
    typeButton: '',
  }
]
const categoryChange1 = ref(null)
const categoryChange2 = ref(null)
const category = ref(null) 
const url = ref({
  get:'/admin/file/searchFile',
  getCategory: '/admin/category/searchCategory',
  updata: '/admin/file/updateFileCategory',
  delete: '/admin/file/deleteFile'
})
const params = ref({
  fileId: undefined,
  categoryId: undefined,
})
const pagination = ref({
    currentPage: 1,
    pageSize: 16,
    totalCount: 0,
    totalPages: 1
})
const categoryList = ref([])
const fileList = ref([])
const checkedAll = ref(false)
const indeterminate = ref(false)
const checkList = ref([])

onMounted(() => { 
  getDataList()
})

const updateCategory = (fileId, newId) => {
  let fileIds
  const indexs = checkList.value
  if (fileId) {
    fileIds = [fileId]
  } else {
    fileIds = checkList.value.map(item => {
      return fileList.value[item].ID
    })
  }
  request.put(url.value.updata, {
    fileIds,
    newCategoryId: newId
  }).then(res => {
    if (res.data.status ==='success') {
      proxy.$message({ type:'success', duration: 1000,  message: res.data.message })
      indexs.forEach(item => {
        categoryChange2.value[item].updateCategory(newId)
      })
      getDataList()
    } else {
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      } else {
        proxy.$message({ type: 'warning', duration: 1000,  message: res.data.message })
      }
    }
  })
}
const isClick = id => {
  return id
}

const handleChange = value => {

}

const handleChangeAll = value => {
  if (indeterminate.value) {
    checkedAll.value = true
    indeterminate.value = false
    checkList.value = fileList.value.reduce((arr, item, index) => {
      arr.push(index)
      return arr
    }, [])
  } else if (checkedAll.value) {
    checkedAll.value = false
    indeterminate.value = false
    checkList.value = []
  } else {
    checkedAll.value = true
    indeterminate.value = false
    checkList.value = fileList.value.reduce((arr, item, index) => {
      arr.push(index)
      return arr
    }, [])
  }
}

const changeImageStatus = (e, index) => {
  if (checkList.value.indexOf(index) === -1) {
    checkList.value.push(index)
  } else {
    checkList.value.splice(checkList.value.indexOf(index), 1)
  }
  if (checkList.value.length > 0) {
    if (checkList.value.length === fileList.value.length) {
      checkedAll.value = true
      indeterminate.value = false
    } else {
      checkedAll.value = false
      indeterminate.value = true
    }
  } else {
    checkedAll.value = false
    indeterminate.value = false
  }
}

const cancelChecked = () => {
  checkedAll.value = false
  indeterminate.value = false
  checkList.value = []
}

const confirmDelete = fileId => {
  let fileIds
  if (fileId) {
    fileIds = [fileId]
  } else {
    fileIds = checkList.value.map(item => {
      return fileList.value[item].ID
    })
  }
  request.delete(url.value.delete, {
    data: { fileIds }
  }).then(res => {
    if (res.data.status ==='success') {
      proxy.$message({ type:'success', duration: 1000,  message: res.data.message })
      getDataList()
    } else {
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      } else {
        proxy.$message({ type: 'warning', duration: 1000,  message: res.data.message })
      }
    }
  })
}

const sizeChange = (page) => {
  pagination.value.currentPage = page
  getDataList()
}

const getDataList = body => {
  request.post(url.value.get, {
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
    ...params.value,
    ...body
  }).then(res => {
    if (res.data.status ==='success') {
      fileList.value = res.data.data
      fileList.value.forEach(item => {
        item.type = getFileTypeFromExtension(item.file_format)
      })
      pagination.value = res.data.pagination
    } else {
      fileList.value = []
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      }
    }
  })

  request.get(url.value.getCategory + '?type=3').then(res => {
    if (res.data.status ==='success') {
      categoryList.value = res.data.data
    } else {
      categoryList.value = []
      if (res.data.errCode >= 500 ) {
        proxy.$message({ type: 'error', duration: 1000,  message: res.data.message })
      } else {
        proxy.$message({ type: 'warning', duration: 1000,  message: res.data.message })
      }
    }
  })
  cancelChecked()
}

const selectCategory = id => {
  pagination.value.currentPage = 1
  params.value.categoryId = id
  getDataList()
}
const updateDate = id => {
  if(id) {
    if (id === params.value.categoryId) {
      category.value.changeCategory(-1)
    }
  }
  getDataList()
}
</script>
-
<template>
  <div class="file-view">
    <yk-space dir="vertical" :size="24">
      <top-title title="本地文件" :titleFunction="titleFunction" :categoryList="categoryList" />
      <Category :categoryList="categoryList" @selectCategory="selectCategory" :type="3" @updateDate="updateDate" ref="category" />
      <yk-space dir="vertical" class="file-content" >
        <yk-space align="center" justify="between" style="width:100%" class="file-content-info">
          <yk-space align="center">
            <yk-checkbox
              :checked="checkedAll"
              :indeterminate="indeterminate"
              @change="handleChangeAll"
            >全选</yk-checkbox>
            <div>已选择 {{ checkList.length }} 项内容</div>
            <a class="cancel-check" @click="cancelChecked" v-if="checkList.length">取消选择</a>
          </yk-space>
          <yk-space :size="16" v-if="checkList.length">
            
            <yk-popconfirm
              title="确认删除吗"
              content="删除后将无法恢复！！！"
              @confirm="confirmDelete"
              style="line-height: 16px;"
              placement="topRight"
            >
              <IconDeleteOutline class="file-action"/>
            </yk-popconfirm>
            <yk-popconfirm
              class="hiddenButton"
              title="请选择分类"
              placement="topRight"
              style="line-height: 16px;"
              auto-adjust-overflow
            >
              <IconSwitchOutline class="file-action"/>
              <template #content>
                <change-category :categoryList="categoryList" ref="categoryChange1" @confirmClick="id => updateCategory(undefined,id)" :categoryIds="checkList" /> 
              </template>
            </yk-popconfirm>
          </yk-space>
        </yk-space>
        <yk-space v-if="fileList.length > 0" :size="[28, 24]" wrap style="padding: 0 18px;">
          <yk-space dir="vertical" :span="16" v-for="(item, index) in fileList" :key="item.ID" align="center">
            <yk-image  class="file-image"
              :class="{'active-img': checkList.includes(index) ? true : false }"
              @click="changeImageStatus($event, index)"
              :preview="false"
              :src="`/src/assets/file/${item.type}.png`"
              width="196"
              height="196"
              title=" "
            >
              <template #extra>
                <yk-space >
                  <yk-space :size="8" class="file-img-action">
                      <yk-popconfirm
                        title="确认删除吗"
                        content="删除后将无法恢复！！！"
                        @confirm="confirmDelete(item.ID)"
                        style="line-height: 30px;"
                      >
                        <div class="image-extra-btn">
                          <IconDeleteOutline />
                        </div>
                      </yk-popconfirm>

                      <yk-popconfirm
                        class="hiddenButton"
                        title="请选择分类"
                        placement="topRight"
                        auto-adjust-overflow
                      >
                        <div class="image-extra-btn">
                          <IconSwitchOutline />
                        </div>
                        <template #content>
                          <change-category :categoryList="categoryList" :categoryId="item.category_id" ref="categoryChange2" @confirmClick="id => updateCategory(item.ID,id)" :categoryIds="checkList"  :index="index" /> 
                        </template>
                      </yk-popconfirm>
                  </yk-space>
                </yk-space>
              </template>
            </yk-image>
            <div class="file-name">{{ item.file_name }}</div>
          </yk-space>
          

        </yk-space>
        <yk-pagination v-if="fileList.length > 0" :default-page-size="pagination.pageSize" v-model:current="pagination.currentPage" :total="pagination.totalCount" style="margin-top: 12px;width:98%;justify-content: flex-end;" @change="sizeChange" />
        <yk-empty v-else style="width:100%;">
          <template #description>
            该分类下暂无文件
          </template>
        </yk-empty>
      </yk-space>
    </yk-space>
  </div>
</template>

<style scoped lang='less'>
.file-view {
  padding: 32px 32px 32px 232px;
  width: 100%;
  background-color: @bg-color-m;

  .file-content {
    width: 100%;
    background-color: @bg-color-l;
    padding: 16px 24px;
    height: 100%;
    border-radius: 8px;

    :deep(.yk-popconfirm.hiddenButton) {
      .yk-tooltip__content {
        .yk-popconfirm__button-group {
          display: none;
        }
      }
    }
    .cancel-check {
      color: @pcolor;
      
      &:hover {
        cursor: pointer;
      }
    }

    .file-image {
      :deep(.yk-image__img) {
          transform: scale(0.2);
        }
      .file-img-action {
        opacity: 0;
        z-index:2;

        :deep(.yk-tooltip__content) {
          width:250px;
        }
        .image-extra-btn {
          height: 30px;
          width: 30px;
          border-radius: 8px;
          background-color: #ffffff8f;
          color:#1e2025;
          line-height: 30px;
          padding: 0 8px;

          &:hover {
            cursor: pointer;
            color: @pcolor;
          }
        }
      }
      &:hover {
       .file-img-action {
          opacity: 1;
        }
        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.2);
          border-radius: 8px;
        } 
      }
    }

    .active-img {
      box-shadow: 0px 0px 10px @lcolor-dark;
    }

    .file-content-info {
      background-color: @bg-color-m;
      border-radius: 8px;
      height:100%;
      padding:16px;

      :deep(.yk-tooltip__content) {
        width:250px;
      }


      .file-action {
        font-size: 18px;
        color:@gray-6;

        &:hover {
          cursor: pointer;
          color:@gray-10;
        }
      }

    }
    
  }
}
</style>